package com.fingard.dsp.bank.directbank.psbc02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.util.TransIDHelper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Date;

public class PSBC02Base extends DirectBase {
    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    public PrivateKey readPrivateKey(String privateKeyFileName, String privatepass) throws Exception {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        FileInputStream fis = new FileInputStream(privateKeyFileName);
        ks.load(fis, null);
        String pwd = privatepass;
        String alias = ((String) ks.aliases().nextElement()).toString();
        PrivateKey prk = (PrivateKey) ks.getKey(alias, pwd.toCharArray());
        return prk;
    }

    protected String[] sendToBank(String reqData) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};
        WriteBankLogStep2(reqData);
        WriteBankLogLn2("银行服务地址:" + bankFront.serverURL);
        WebRequest tmpRequest = new WebRequest(bankFront.serverURL);
        tmpRequest.setConnectTimeout(100000);
        tmpStrRet = tmpRequest.upload(reqData.getBytes(getCharset()), getCharset());
        WriteBankLogStep3(tmpStrRet[1]);
        return tmpStrRet;
    }
}